use crate::app::server::message;
use serde::{Deserialize, Serialize};

pub(crate) type Result<T> = std::result::Result<T, String>;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CommonMsg {
    status: i32,
    message: String,
    data: Vec<u8>,
}

impl CommonMsg {
    pub fn default() -> Self {
        CommonMsg {
            status: 200,
            message: String::new(),
            data: vec![],
        }
    }
    pub fn new(s:i32, d:Vec<u8>) -> Self {
        CommonMsg {
            status: s,
            message: String::new(),
            data: d,
        }
    }
    pub fn new_from_vec(data: &Vec<u8>) -> Result<Self> {
        match serde_json::from_slice(data.as_slice()) {
            Err(e) => Err(e.to_string()),
            Ok(o) => Ok(o),
        }
    }

    pub fn to_message(&self, header: u16) -> Result<message::Message> {
        let mut msg = message::Message::new_null();
        msg.encode_from_json(&self)?;
        msg.set_header(header);
        Ok(msg)
    }

    pub fn set_status(mut self, status: i32) -> Self {
        self.status = status;
        self
    }
    pub fn set_message(mut self, msg: &str) -> Self {
        self.message = msg.clone().to_string();
        self
    }
    pub fn set_data(&mut self, data: Vec<u8>) {
        self.data = data;
    }
    pub fn set_data_from_struct<T: Serialize>(&mut self, t: &T) -> Result<()> {
        match serde_json::to_vec(t) {
            Err(e) => Err(e.to_string()),
            Ok(o) => {
                self.set_data(o);
                Ok(())
            }
        }
    }
}
